/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.bfh.aeneas.core.io.tts;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.widget.EditText;
import ch.bfh.aeneas.R;
import ch.bfh.aeneas.core.io.tts.bloomfilter.LangFinder;
import ch.bfh.aeneas.exchange.intent.AeneasIntent;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;




/**
 * <p>Demonstrates text-to-speech (TTS). Please note the following steps:</p>
 *
 * <ol>
 * <li>Construct the TextToSpeech object.</li>
 * <li>Handle initialization callback in the onInit method.
 * The activity implements TextToSpeech.OnInitListener for this purpose.</li>
 * <li>Call TextToSpeech.speak to synthesize speech.</li>
 * <li>Shutdown TextToSpeech in onDestroy.</li>
 * </ol>
 *
 * <p>Documentation:
 * http://developer.android.com/reference/android/speech/tts/package-summary.html
 * </p>
 * <ul>
 */
public class TextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener {

    private static final String TAG = "TextToSpeechDemo";

    private TextToSpeech mTts;
    private Button mAgainButton;
    private Locale inLoc;
    private String hello;
    private EditText hellotemp;
    private LangFinder mLF;
    
    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.text_to_speech);
            
                mLF = new LangFinder(this);
            
            // Initialize text-to-speech. This is an asynchronous operation.
            // The OnInitListener (second argument) is called after initialization completes.
            mTts = new TextToSpeech(this,
                this  // TextToSpeech.OnInitListener
                );

            // The button is disabled in the layout.
            // It will be enabled upon initialization of the TTS engine.
            mAgainButton = (Button) findViewById(R.id.again_button);

            mAgainButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    hellotemp = (EditText) findViewById(R.id.inputfield);
                    hello=hellotemp.getText().toString();
                    //speech();
                    Intent output = new Intent(AeneasIntent.ACTION_OUTPUT);
                    output.putExtra("Speech", hello);
                    sendBroadcast(output);
                
                    
                    //Log.i(TAG,"Click");
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(TextToSpeechActivity.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }

        super.onDestroy();
    }

    // Implements TextToSpeech.OnInitListener.
    public void onInit(int status) {
        
            mTts.setLanguage(inLoc);
 
    }

    public String readGoogleLanguageDetection(String findword) {
                String s=null;
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(
				"https://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+findword);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
//				String line;
//				while ((line = reader.readLine()) != null) {
//					builder.append(line);
                                //}
                                s = reader.readLine();
			
			} else {
				Log.e(TAG, "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//return builder.toString();
                
                try {
                                JSONObject post = new JSONObject(s);
                                s=post.getJSONObject("responseData").getString("language");

                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                
                return s;
	}
    
    public ArrayList<ArrayList> splitSentenceToLang(String inSen)
    {
        //Log.i(TAG,"in methode splitSentence");
        int[][] output=null;
        String[] words = inSen.split(" ");
        int[] lang = new int[words.length];
        ArrayList<ArrayList> LangBlocksAL=new ArrayList();
        ArrayList<ArrayList> PostProzessAL=new ArrayList();
        ArrayList<String> ToSpeechAL=new ArrayList();

        for(int i=0;words.length>i;i++)
        {
            //lang[i]=getLangCode(readGoogleLanguageDetection(words[i]));
            lang[i]=getLangCode(mLF.getLang(words[i]));
            //Log.i(TAG,words[i]+" mit Index: "+i+" is: "+lang[i]);
        }
        
        //words to LangBlocks
        LangBlocksAL=intbuildLangBlocks(lang,words);
        
        //Failure search and eliminate
//        for(int i=0;LangBlocksAL.size()>i;i++)
//        {
//           ToSpeechAL.add(LangBlocksAL.get(i).get(1).toString());
//           for(int q=0;LangBlocksAL.size()>q;q++)
//            {
//               ToSpeechAL.add(LangBlocksAL.get(i).get(q).toString());
//            }
//        }
        
        return LangBlocksAL;
    }
    
    public ArrayList<ArrayList> intbuildLangBlocks(int[] sntPart, String[] textA)
    {
        ArrayList<String> blockArray;
        ArrayList<ArrayList> outArray=new ArrayList();
        boolean Notend=true;
        int z =0;
        
        for(int i = 0; i < sntPart.length; i++)
        {
            if(Notend)
            {
                //blockArray.add(sntPart[i]);
                //Log.i(TAG,"Sprache: "+sntPart[i]);
                 blockArray = new ArrayList();
                 blockArray.add(Integer.toString(sntPart[i]));
                for(int j = i; j < sntPart.length; j++)
                {
                    if(sntPart[i] == sntPart[j])
                    {
                        //Log.i(TAG,"Index gehört dazu: "+j);
                        blockArray.add(textA[j]);
                        if(j==(sntPart.length-1))
                        {
                            outArray.add(blockArray);
                            //Log.i(TAG,blockArray.toString());
                            Notend=false;
                            break;
                        }
                    }
                    else
                    {
                         i = j-1;
                         //Log.i(TAG,blockArray.toString());
                         outArray.add(blockArray);
                         //blockArray.clear();
                         z++;
                        break;
                    }
                }
            }
        }
        Log.i(TAG,outArray.toString());
        return outArray;
    }
    
//    private ArrayList<Integer> intbuildLangBlocks(int[] sntPart,int startInd,int stopInd)
//    {
//        ArrayList<ArrayList> outArray=new ArrayList();
//        int partLenght=(stopInd-startInd);
//        
//        ArrayList<Integer> blockArray=new ArrayList();
//        int i;
//        for(i=startInd;i<partLenght;i++)
//        {
//            blockArray.add(i);
//            if(sntPart[i]==sntPart[i+1])
//            {
//                blockArray.add(i+1);
//            }
//            else
//            {
//                
//                outArray.add(intbuildLangBlocks(sntPart,i,stopInd));
//            }
//        }
//        
//        
//        
//    }
    
    
    private Locale findLocal(int gld)
    {
        Locale l=Locale.US;
        if(gld==0)
        {
             l=Locale.US;
        }
        else if(gld==1)
        {
            l=Locale.FRENCH;
        }
        else if(gld==2)
        {
            l=Locale.GERMAN;
        }
        
        return l;

    }
    
    public int getLangCode(String inStr) 
    {
        Log.i(TAG,"getLangCode "+inStr);
        if(inStr.equals("en"))
        {
            return 0;
        }
        else if(inStr.equals("fr"))
        {
            return 1;
        }
        else if(inStr.equals("de"))
        {
            return 2;
        }
        else
        {
            return -1;
        }
    } 
    
    
    private void speech() {
        // Select a random hello.
        new Thread()
                {
            @Override
                    public void run()
                            {
                                //Log.i(TAG,"In run");
                                ArrayList<ArrayList> WordBlocksAL;
                                //String hello = "Hier ist die Strasse rue du general de nom behind this building";
                                
                                //Remember to deactivate in tts settings "use always my Settings" on the android device!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
                                WordBlocksAL=splitSentenceToLang(hello);
                                //Log.i(TAG,"ArrayList to speek is: "+WordBlocksAL.toString());                                
                                for(int i=0;WordBlocksAL.size()>i;i++)
                                {
                                    inLoc=findLocal(Integer.parseInt(((WordBlocksAL.get(i)).get(0)).toString()));
                                    Log.i(TAG,"Locale is: "+inLoc.toString());
                                    String out="";
                                    
                                    for(int j=1;(WordBlocksAL.get(i)).size()>j;j++)
                                    {   
                                        //Log.i(TAG,"In size: "+(WordBlocksAL.get(i)).size());
                                        out=out.concat(((WordBlocksAL.get(i)).get(j)).toString());
                                        //Log.i(TAG,"Text: "+((WordBlocksAL.get(i)).get(j)).toString());
                                        out=out.concat(" ");
                                    }
                                    //Log.i(TAG,"Read string is: "+out);
                                    onInit(0);
                                    mTts.speak(out,TextToSpeech.QUEUE_ADD,null);
                                }
       
                            }
                }.start();
    }
}
